package com.example.lin.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.lin.util.DateUtils;
import com.example.lin.util.ExportUtil;
import com.example.lin.util.ImportUtil;
import com.example.lin.util.MD5Utils;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 嘉兴小包换单工具
 *
 * @author GuLin
 * @create 2025-05-31 11:49
 */
public class PackageJXInfo {

    @Test
    public void sendJxInfo() {

        RestTemplate restTemplate = RestTemplateProxy.getRestTemplate();

        String filePath = "D:\\test\\嘉兴业务处理.xlsx";
        int sheet = 0;
        List<List<Object>> list = ImportUtil.readExcelToList(filePath, sheet);
        AtomicInteger i = new AtomicInteger();
        List<Object[]> data = new ArrayList<>();
        data.add(new Object[]{"订单号", "短号", "换单重量", "长", "宽", "高"});
        list.forEach(e -> {
            int andIncrement = i.getAndIncrement();
            String messageId = DateUtils.format(new Date(), DateUtils.YMDHS_FORMAT) + String.format("%06d", andIncrement);
            String scanPackageTime = DateUtils.format(new Date(), DateUtils.DEFAULT_DATETIME_FORMAT);
            String trackingNumber = e.get(0).toString();
            String referenceNumber = e.get(1).toString();
            if(referenceNumber.length() != 15){
                System.out.println("订单短号长度不对,请检查");
                return;
            }
            String packageWeight = e.get(2).toString();
            String packageLength = StringUtils.isEmpty(e.get(3).toString()) ? null : e.get(3).toString();
            String packageWidth = StringUtils.isEmpty(e.get(4).toString()) ? null : e.get(4).toString();
            String packageHeight = StringUtils.isEmpty(e.get(5).toString()) ? null : e.get(5).toString();

            long timeStamp = System.currentTimeMillis();

            String url = "http://10.30.20.50:9099/api/vendor/sino/package/v1/packages";
            String prams = "{\n" +
                    "    \"data\": {\n" +
                    "        \"facilitycode\": \"08\",\n" +
                    "        \"trackingNumber\": \"" + referenceNumber + "\",\n" +
                    "        \"referenceNumber\": \"" + referenceNumber + "\",\n" +
                    "        \"packageWeight\": \"" + packageWeight + "\",\n" +
                    "        \"operateUser\": \"00002\",\n" +
                    "        \"scanPackageTime\": \"" + scanPackageTime + "\",\n" +
                    "        \"packageLength\": " + packageLength + ",\n" +
                    "        \"packageWidth\": " + packageWidth + ",\n" +
                    "        \"packageHeight\": " + packageHeight + ",\n" +
                    "        \"packageBattery\": false,\n" +
                    "        \"destination\": null,\n" +
                    "        \"serviceName\": null,\n" +
                    "        \"packingStable\": \"0\"\n" +
                    "    },\n" +
                    "    \"messageId\": \"" + messageId + "\",\n" +
                    "    \"timestamp\": \"" + timeStamp + "\"\n" +
                    "}";
            //System.out.println("请求报文: " + prams);
            System.out.println("请求单号: " + trackingNumber);

            String apiKey = "996061f0-5011-47fb-b308-372649626153";
            String secretKey = "19ed94e8-23af-4185-87b0-c1d6b1513a8c";
            String requestUri = url.split(":9099")[1];

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
            headers.add("apiKey", apiKey);

            //校验签名结果是否正确
            String signString = new StringBuffer(requestUri).append("|")
                    .append(prams).append("|")
                    .append(apiKey).append("|")
                    .append(secretKey).toString();
            String auth = MD5Utils.sign(signString, "utf-8");
            headers.add("authorization", auth);
            headers.add("timeStamp", timeStamp + "");

            HttpEntity<String> entity = new HttpEntity(prams, headers);
            try {
                String result = restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();
                //System.out.println("响应报文: " + JSON.toJSONString(result));
                JSONObject jsonObject = JSON.parseObject(result);
                JSONObject result1 = JSON.parseObject(jsonObject.getObject("data", String.class));
                String lastmileTrackingNumber = result1.getString("lastmileTrackingNumber");
                if (StringUtils.isEmpty(lastmileTrackingNumber)) {
                    throw new RuntimeException("处理异常");
                }
                System.out.println("处理成功响应单号: " + (trackingNumber + "_" + lastmileTrackingNumber));
            } catch (Exception exception) {
                System.out.println("处理异常单号: " + trackingNumber);
                data.add(new Object[]{trackingNumber, referenceNumber, packageWeight, packageLength, packageWidth, packageHeight});
            }
        });
        if (data.size() > 1) {
            ExportUtil.exportTheFile("嘉兴业务处理", data);
            System.out.println("再次重试失败单号条数:" +  (data.size()-1));
        } else {
            System.out.println("处理完成");
        }

    }

}
